# 負責管理電報的控制器.
class ComputersController < ApplicationController
  
  # 除了新增,顯示單筆資料外,其它方法都要登入才能使用.
  before_filter :authorize, :except => [:new, :create, :show]
  
  # 只有顯示電報外要先紀錄目前的 URL .
  before_filter :record_uri, :only => [:show]

  # 只有顯示電報和新增電報外要最愛電報清單 .
  before_filter :find_favorite, :only => [:show, :create, :new]
  
  
  # GET /computers
  # GET /computers.xml
  def index
#    @computers = Computer.find(:all)
    @computers = Computer.paginate(:page => params[:page], :per_page => 5, :order => 'updated_at DESC')

    respond_to do |format|
      format.html # index_sort_by_updated_at_desc.html.erb
      format.xml  { render :xml => @computers }
    end
  end

  # GET /computers/1
  # GET /computers/1.xml
  def show
    begin
      @computer = Computer.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("使用者嘗試存取錯誤的電報 #{params[:id]}")
#      flash[:notice] = "查無此電報"
      redirect_to_error_page
    else
      @posts = @computer.posts
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @computer }
      end
    end
  end

  # GET /computers/new
  # GET /computers/new.xml
  def new
    @computer = Computer.new
    put_noisy_image_into_session

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @computer }
    end
  end

  # GET /computers/1/edit
  def edit
    @computer = Computer.find(params[:id])
  end

  # POST /computers
  # POST /computers.xml
  def create
    @computer = Computer.new(params[:computer])

    # 驗證圖片數字是否吻合.
    unless params[:typed_code] == session[:noisy_image].code
      flash[:notice] = '驗證碼錯誤'
      redirect_to(:action => :new) and return false
    else
      respond_to do |format|
        if @computer.save # Model 的 Validate 會先檢查.
          flash[:notice] = '新增電報成功'
          format.html { redirect_to(@computer) }
          format.xml  { render :xml => @computer, :status => :created, :location => @computer }
        else
          format.html { render :action => :new }
          format.xml  { render :xml => @computer.errors, :status => :unprocessable_entity }
        end
      end
    end
    
  end

  # PUT /computers/1
  # PUT /computers/1.xml
  def update
    @computer = Computer.find(params[:id])

    respond_to do |format|
      if @computer.update_attributes(params[:computer])
        flash[:notice] = '更新電報成功'
        format.html { redirect_to(@computer) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @computer.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /computers/1
  # DELETE /computers/1.xml
  def destroy
    @computer = Computer.find(params[:id])
    @computer.destroy
    
    flash[:notice] = '刪除電報成功'
    respond_to do |format|
      format.html { redirect_to(computers_url) }
      format.xml  { head :ok }
    end
  end
  
end
